import json

from django.http import JsonResponse

from mech_manage.models import Project


def dispatcher(request):
    # 将请求同意放在request的params中
    print(request.body)
    if request.method == 'GET':
        request.params = request.GET
    elif request.method in ['POST', 'PUT', 'DELETE']:
        request.params = json.loads(request.body)

    # 根据不同的action分派给不同的函数进行处理
    action = request.params['action']
    # if action == 'find_project':
    #     return find_project(request)
    if action == 'list_project':
        return list_project(request)
    elif action == 'add_project':
        return add_project(request)
    elif action == 'modi_project':
        return modi_project(request)
    elif action == 'del_project':
        return del_project(request)

    else:
        return JsonResponse({'ret': 1, 'msg': '不支持该类型http请求'}, json_dumps_params={'ensure_ascii': False})


# def find_project(request):
#     # 读取传来的用户名密码
#
#     try:
#         dname = request.params['project']
#         dkachu = request.params['name']
#         project = Project.objects.get(Dname=dname, Dkachu=dkachu)
#         return JsonResponse({
#             'ret': 0
#         }, json_dumps_params={'ensure_ascii': False})
#     except Project.DoesNotExist:
#         return JsonResponse({
#             'ret': 1,
#             'msg': f'部门信息或负责人错误，请重新输入'
#         }, json_dumps_params={'ensure_ascii': False})


def list_project(request):
    # 返回一个 QuerySet 对象 ，包含所有的表记录
    qs = Project.objects.values()
    # 将 QuerySet 对象 转化为 list 类型
    # 否则不能 被 转化为 JSON 字符串
    retlist = list(qs)
    return JsonResponse({'ret': 0, 'retlist': retlist}, json_dumps_params={'ensure_ascii': False})


def add_project(request):
    info = request.params['data']
    # 从请求消息中获取要添加的人员信息，并插入到数据库，返回值就是被插入的记录对象
    try:
        record = Project.objects.create(Prname=info['name'],
                                       Prmanager=info['manager'],
                                       Prmassort=info['massort'],
                                       Prmassage=info['massage'],
                                       )
        return JsonResponse({'ret': 0, 'id': record.id}, json_dumps_params={'ensure_ascii': False})
    except:
        return JsonResponse({'ret': 1, 'msg': "操作失败，信息不全"}, json_dumps_params={'ensure_ascii': False})


def modi_project(request):
    projectid = request.params['id']

    newdata = request.params['newdata']

    try:
        project = Project.objects.get(id=projectid)
    except Project.DoesNotExist:
        return JsonResponse({
            'ret': 1,
            'msg': f'id为‘{projectid}’的部门不存在'
        }, json_dumps_params={'ensure_ascii': False})
    """
    原有写法
    """
    # if 'name' in newdata:
    #     project.Pname = newdata['name']
    # if 'level' in newdata:
    #     project.Plevel = newdata['level']
    # if 'password' in newdata:
    #     project.Ppassword = newdata['password']
    # if 'project' in newdata:
    #     project.Pproject = newdata['project']
    # if 'sort' in newdata:
    #     project.Psort = newdata['sort']
    # if 'state' in newdata:
    #     project.Pstate = newdata['state']
    # if 'starttime' in newdata:
    #     project.Pstarttime = newdata['starttime']
    # if 'endtime' in newdata:
    #     project.Pendtime = newdata['endtime']
    # """
    """
    效率写法
    """
    for keys in newdata.keys():
        # print(keys)
        # print("project.P"+keys+"=newdata['"+keys+"']")
        if len(keys) > 15:
            return JsonResponse({'ret': 1,
                                 'msg': f'侦测到潜在的入侵行为'
                                 }, json_dumps_params={'ensure_ascii': False})
        exec("project." + keys + "=newdata['" + keys + "']")
        exec("print(project." + keys + ")")
    # """
    project.save()

    return JsonResponse({'ret': 0}, json_dumps_params={'ensure_ascii': False})


def del_project(request):
    projectid = request.params['id']

    try:
        project = Project.objects.get(id=projectid)
    except Project.DoesNotExist:
        return JsonResponse({
            'ret': 1,
            'msg': f'要删除的项目不存在'
        }, json_dumps_params={'ensure_ascii': False})
    # delete 方法就将该记录从数据库中删除了
    project.delete()

    return JsonResponse({'ret': 0}, json_dumps_params={'ensure_ascii': False})
